/**
 * 
 */
package com.vector.ding.web.service;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.vector.ding.commons.ActionResult;
import com.vector.ding.commons.Constant;
import com.vector.ding.commons.util.StringUtil;
import com.vector.ding.commons.util.collection.CollectionUtil;
import com.vector.ding.dao.mybatis.mapper.UserMapper;
import com.vector.ding.dao.mybatis.mapper.UserMenuAuthMapper;
import com.vector.ding.dao.mybatis.model.User;
import com.vector.ding.dao.mybatis.model.UserExample;
import com.vector.ding.dao.mybatis.model.UserMenuAuth;
import com.vector.ding.dao.mybatis.model.UserMenuAuthExample;

/**
 * @author 丁窍
 *
 */
@Service
public class UserService {
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserMenuAuthMapper menuAuthMapper;
	
	public Object getUserList() {
		// 执行完select语句后，page引用的对象指向查询结果，即ArrayList<EmapUser>
		@SuppressWarnings("unchecked")
		Page<User> page = PageHelper.startPage(0, 10, true);
		UserExample e = new UserExample();
		e.setOrderByClause("id asc");
		List<User> userList = userMapper.selectByExample(e);
		System.out.println(page);  
		
		return JSONArray.fromObject(userList);
	}
	
	public List<User> getUsers(int pageIndex, int pageSize, HttpServletRequest request) {
		@SuppressWarnings("unchecked")
		Page<User> page = PageHelper.startPage(pageIndex, pageSize, true);
		UserExample e = getUserSearchExample(request);
		e.or().andNameNotEqualTo("admin");
		e.setOrderByClause("number asc");
		userMapper.selectByExample(e);
		hiddenUserPwd(page);
		return page;
	}
	
	private UserExample getUserSearchExample(HttpServletRequest request) {
		UserExample e = new UserExample();
		UserExample.Criteria criteria = e.createCriteria();
		String number = request.getParameter("number");
		if (StringUtil.isNotEmpty(number))
			criteria.andNumberLike(StringUtil.wrapString(number, "%", "%"));
		String name = request.getParameter("name");
		if (StringUtil.isNotEmpty(name))
			criteria.andNameLike(StringUtil.wrapString(name, "%", "%"));
		String sex = request.getParameter("sex");
		if (StringUtil.isNotEmpty(sex))
			criteria.andSexEqualTo(sex);
		String department = request.getParameter("department");
		if (StringUtil.isNotEmpty(department))
			criteria.andDepartmentLike(StringUtil.wrapString(department, "%", "%"));
		String position = request.getParameter("position");
		if (StringUtil.isNotEmpty(position))
			criteria.andPositionLike(StringUtil.wrapString(position, "%", "%"));
		
		return e;
	}
	
	public List<User> getUsers() {
		List<User> users = userMapper.selectByExample(null);
		hiddenUserPwd(users);
		return users;
	}
	
	private void hiddenUserPwd(List<User> users) {
		if (CollectionUtil.isEmpty(users))
			return ;
		
		for (User user: users) {
			user.setPassword("***");
		}
	}
	
	public boolean addUser(User user) {
		if (StringUtil.isEmpty(user.getId()))
			user.setId(UUID.randomUUID().toString());
		return 1 == userMapper.insertSelective(user);
	}
	
	public boolean updateUser(User user) {
		if (StringUtil.isEmpty(user.getId()))
			return false;
		return 1 == userMapper.updateByPrimaryKeySelective(user);
	}
	
	public void deleteUser(String... userIds) {
		if (userIds == null)
			return ;
		
		for (String usetId: userIds) {
			userMapper.deleteByPrimaryKey(usetId);
		}
	}
	
	public User parseUser(HttpServletRequest request) {
		User user = new User();
		user.setNumber(request.getParameter("number"));
		user.setDepartment(request.getParameter("department"));
		user.setEmail(request.getParameter("email"));
		user.setName(request.getParameter("name"));
		String password = request.getParameter("password");
		if (StringUtil.isNotEmpty(password) && !password.equals(Constant.HIDDEN_PWD))
			user.setPassword(new Md5Hash(password).toString());
		user.setPosition(request.getParameter("position"));
		user.setSex(request.getParameter("sex"));
		if (StringUtil.isEmpty(request.getParameter("id")))
			user.setId(UUID.randomUUID().toString());
		else
			user.setId(request.getParameter("id"));
		
		return user;
	}
	
	public User getUser(String userId) {
		return userMapper.selectByPrimaryKey(userId);
	}
	
	public Set<String> getUserMenuSet(String userId) {
		UserMenuAuthExample example = new UserMenuAuthExample();
		example.or().andUserIdEqualTo(userId);
		List<UserMenuAuth> authList = menuAuthMapper.selectByExample(example);
		if (CollectionUtil.isEmpty(authList))
			return Collections.emptySet();
		
		Set<String> menus = new HashSet<String>();
		for (UserMenuAuth auth: authList) {
			menus.add(auth.getMenuId());
		}
		return menus;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	
	public void deletUserMenuAuth(String userId) {
		UserMenuAuthExample example = new UserMenuAuthExample();
		example.or().andUserIdEqualTo(userId);
		menuAuthMapper.deleteByExample(example);
	}

	public JSONObject saveMenuAuth(String userId, String... menuArray) {
		if (menuArray == null || menuArray.length == 0)
			return ActionResult.success();
		
		for (String menu: menuArray) {
			if (StringUtil.isEmpty(menu))
				continue;
			
			UserMenuAuth uma = new UserMenuAuth();
			uma.setId(StringUtil.getUuid());
			uma.setUserId(userId);
			uma.setMenuId(menu);
			menuAuthMapper.insert(uma);
		}
		
		return ActionResult.success();
	}

}